
import React, { useState, useEffect } from 'react'
import { Table, Pagination, Button, Input, Modal, Form, Select, message } from 'antd';
import axios from 'axios';


export default function NoQrCode() {
  const [open, setOpen] = useState(false);
  const [selectionType, setSelectionType] = useState('checkbox');
  const [dataSource, setDataSource] = useState([])
  const [dataTotal, setDataTotal] = useState([])
  const [option, setOption] = useState([])
  const [nowOption, setNowOption] = useState([])
  const [btnText, setBtnText] = useState("连接扫码枪")
  const [proId, setProId] = useState("")
  const [proItem, setProItem] = useState("")
  const [messageApi, contextHolder] = message.useMessage();
  const handleChange = (value) => {
    setNowOption(value)
  };
  const CollectionCreateForm = ({ open, onCreate, onCancel }) => {
    const [form] = Form.useForm();

    return (
      <Modal
        open={open}
        title="读取标识码"
        okText="确定"
        cancelText="取消"
        onCancel={onCancel}
        onOk={() => {
          form
            .validateFields()
            .then((values) => {
              form.resetFields();
              onCreate(values);
            })
            .catch((info) => {
              console.log('Validate Failed:', info);
            });
        }}
      >
        <Form
          form={form}
          layout="vertical"
          name="form_in_modal"
          initialValues={{
            modifier: 'public',
          }}
        >
          <Form.Item
            name="code"
            label="标识码"
            rules={[
              {
                required: true,
                message: '未获取到标识码！',
              },
            ]}
            initialValue={proId}
          >
            <Input disabled />
          </Form.Item>
        </Form>
      </Modal>
    );
  };
  const onCreate = (values) => {
    axios.post("/com/updatepro", { "productid": values.code, "id": proItem.id }).then(res => {
      if (res.data) {
        var data = [...dataSource.filter(obj => {
          return obj.id !== proItem.id
        })]
        setDataSource(data)
        setDataTotal(data.length)
      } else {
        messageApi.info("贴码失败！")
      }

    })

    setOpen(false);
  };
  const rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
    },
    getCheckboxProps: (record) => ({
      disabled: record.name === 'Disabled User',
      // Column configuration not to be checked
      name: record.name,
    }),
  };
  useEffect(() => {
    axios.get("/product/selectpro?type=2").then(res => {
      setDataSource(res.data)
      setDataTotal(res.data.length)
    })
    axios.get("/com/selectcom").then(res => {
      setOption(res.data)
      setNowOption(res.data[0].value)
    })
  }, [])
  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      align: "center",
      fixed: "left",
      width: "5%",
      render: (text, record, index) => {
        return <span style={{ fontSize: "12px" }}>{index + 1}</span>
      }
    },
    {
      title: '产品名称',
      dataIndex: 'productname',
      key: 'productName',
      align: "center",
      fixed: "left",
      render: (text) => {
        return <span style={{ fontSize: "12px" }}>{text}</span>
      }
    },
    {
      title: '类型',
      dataIndex: 'producttype',
      key: 'productType',
      align: "center",
      render: (text) => {
        return <span style={{ fontSize: "12px" }}>{text}</span>
      }
    },
    {
      title: '产品品牌',
      dataIndex: 'productbrand',
      key: 'productBrand',
      align: "center",
      render: (text) => {
        return <span style={{ fontSize: "12px" }}>{text}</span>
      }
    },
    {
      title: "生产日期",
      dataIndex: 'producttime',
      key: 'productTime',
      align: "center",
      className: "wrapTitle",
      render: (text) => {
        return <span style={{ fontSize: "12px" }}>{text}</span>
      }
    },
    {
      title: '操作',
      align: "center",
      width: "100px",
      render(item) {
        return (
          <Button style={{ color: "black", fontSize: "12px", borderRadius: "4px", margin: "0 0 0 10px" }} onClick={() => { setOpen(true); setProItem(item) }}>贴码</Button>

        )
      }
    }
  ];

  const openCom = () => {
    if (btnText === "连接扫码枪") {
      axios.get("/com/opencom?com=" + nowOption).then(res => {
        if (res.data !== 500) {
          if (res.data !== 200) {
            setBtnText("断开扫码枪")
            setProId(res.data)
          }

        } else {
          messageApi.info('连接失败!');
          setBtnText("连接扫码枪")
          axios.get("/com/closecom").then(res => {
            messageApi.info('请重新连接!');

          })
        }

      })
      setBtnText("断开扫码枪")
    } else {
      axios.get("/com/closecom").then(res => {
        if (res.data) {
          messageApi.info('断开成功!');
          setBtnText("连接扫码枪")
        } else {
          messageApi.info('断开失败!');
        }

      })
    }

  }
  return (
    <div>
      {contextHolder}
      <div >
        <Select
          style={{
            width: 150,
            textAlign: "left"
          }}
          value={nowOption}
          onChange={handleChange}
          options={option}
        />
        <Button type='primary' style={{ color: "white", fontSize: "12px", borderRadius: "4px", margin: "0 0 0 10px" }} onClick={() => { openCom() }}>{btnText}</Button>
      </div>
      <Table
        rowSelection={{
          type: selectionType,
          ...rowSelection,
        }}
        rowKey={(item) => item.id}
        columns={columns} dataSource={dataSource} style={{ margin: "5px 0 0 0" }}
        pagination={{ pageSize: 10 }}
        size='small'
        scroll={{ x: 1200 }}
      >
      </Table>
      <CollectionCreateForm
        open={open}
        onCreate={onCreate}

        onCancel={() => {
          setOpen(false);
        }}
      />
    </div>
  )
}
